package com.topvision.controller;

import com.topvision.common.response.SuccessResponse;
import com.topvision.common.tree.TreeNode;
import com.topvision.common.tree.TreeUtil;
import com.topvision.domain.SysGroup;
import com.topvision.service.GroupBaseService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/group")
@Api(value = "分组信息", description = "组相关操作")
@Slf4j
public class GroupController {

    @Autowired
    private GroupBaseService groupBaseService;


    /**
     * 创建分组
     *
     * @param title
     * @param parentId
     * @return
     */
    @GetMapping("/createGroup/{title}/{parentId}")
    public ResponseEntity createGroup(@PathVariable String title, @PathVariable String parentId) {
        SysGroup group = new SysGroup();
        Long parent = Long.valueOf(parentId);
        group.setName(title);
        group.setParentId(parent);
        groupBaseService.save(group);
        return ResponseEntity.ok(SuccessResponse.of(group));
    }

    /**
     * 根据用户名查询其下分组
     *
     * @param username
     * @return
     */
    @GetMapping("/findByUser/{username:.+}")
    public ResponseEntity findByCreater(@PathVariable String username) {
        Map<String, Object> params = new HashMap<>();
        params.put("createdBy", username);
        List<SysGroup> groups = groupBaseService.list(params);
        List<TreeNode<SysGroup>> treeNodes = new ArrayList<>();
        for (SysGroup sysGroup : groups) {
            TreeNode<SysGroup> treeNode = new TreeNode<>();
            treeNode.setId(sysGroup.getId().toString());
            treeNode.setParentId(sysGroup.getParentId().toString());
            treeNode.setText(sysGroup.getName());
            treeNode.setData(sysGroup);
            treeNode.setSort(0);
            treeNodes.add(treeNode);
        }
        List<TreeNode> list = TreeUtil.build(treeNodes);
        return ResponseEntity.ok(SuccessResponse.of(list));
    }


    @PostMapping("/editgroup")
    public ResponseEntity addDevice(@RequestBody SysGroup sysGroup) {
        if (sysGroup != null) {
            groupBaseService.save(sysGroup);
        }
        return ResponseEntity.ok(SuccessResponse.of(sysGroup));
    }

    @PostMapping("/delgroup/{groupId}")
    public ResponseEntity delGroup(@PathVariable String groupId) {
        if (groupId != null) {
            groupBaseService.del(Long.valueOf(groupId));
        }
        return ResponseEntity.ok(SuccessResponse.of());
    }


}
